define([ "modules/ep" ], function(ep) {
	return {
		/*
		 * id, formId, title, url
		 */
		createFormWindow: function(config) {
			require([ "dijit/Dialog", "dijit/form/Button", "modules/ep"], function(dialog, button, thisObj) {
				var onSuccess = function(response) {
					thisObj.createActionDialog({
						id: config.id,
						title: config.title,
						content: response,
						beforeSubmit: function() { },
						onSuccess: function() {
							thisObj.sendForm(config.formId ,config.onSuccess);
						}
					}) 
				}
				thisObj.requestGet(config.url, onSuccess);
				
			});
		},
		createPostWindow : function(config) {
			require([ "dijit/Dialog", "dijit/form/Button", "modules/ep"], function(dialog, button, thisObj) {
				var onSuccess = function(response) {
					thisObj.createActionDialog({
						id: config.id,
						title: config.title,
						content: response,
						beforeSubmit: (config.beforeSubmit !== "undefined") ? config.beforeSubmit : function() {},
						onSuccess: function() {
						    dojo.xhrPost({
						        url: config.postUrl,
						        content: config.postQueryObject,
						        load: function(response, ioArgs) {
						            config.onSuccess(response);
						        },
						        error : function(error) {
						        }
						    });
						}
					}) 
				};
				thisObj.requestGet(config.windowUrl, onSuccess);
				
			});
		}
		,
		/*
		 * Wysyla formularz formId , callback - onSuccess
		 */
		sendForm: function(formId, onSuccess) {
			require(["dojo/_base/lang", "dojo/_base/xhr", "modules/ep"], function(lang, xhr, thisObj){
			    xhr.post({
			       form: formId,
			       load: function(data, ioArgs){
			    	   onSuccess(data);
			       },
			       error: function(err, ioArgs){
						alert(error);
			       }
			    });
		    });
		},
		/*
		 * Wyswietla msg na ekranie @param: text
		 */
		showMsg: function(text) {
			require([ "dijit/Dialog", "dijit/form/Button"], function(dialog, Button) {
				var dlg = new dijit.Dialog({
					id : 'messageWindow',
					title : 'Informacja',
					content: "" + text,
					onHide : function() {
						dijit.byId('messageWindow').destroyRecursive();
					}
				});
				
                var yesBtn = new Button({
                    label: "OK",
                    style : "margin: auto; padding-top: 20px; padding-bottom: 5px",
                    onClick : function() {
                        dlg.hide();
                    }
                 });

                var div = dojo.create('div', { style : {'text-align' : "center" } }, dlg.containerNode);
                dojo.create(yesBtn.domNode,{}, div);
				dlg.show();
			});
		},
		showMsgExecuteAfterClose: function(text, onClose) {
			require([ "dijit/Dialog" ], function(dialog) {
				var dlg = new dijit.Dialog({
					id : 'messageWindow',
					title : 'Informacja',
					content: text,
					onHide : function() {
						dijit.byId('messageWindow').destroyRecursive();
						onClose();
					}
				});
				
                var yesBtn = new dijit.form.Button({
                    label: "OK",
                    style : "margin: auto; padding-top: 20px; padding-bottom: 5px",
                    onClick : function() {
                        dlg.hide();
                        onClose();
                    }
                 });

                var div = dojo.create('div', { style : {'text-align' : "center" } }, dlg.containerNode);
                dojo.create(yesBtn.domNode,{}, div);
				dlg.show();
			});
		},
		showMsgCustom: function(text, tittle) {
			require([ "dijit/Dialog", "dijit/form/Button"], function(dialog, Button) {
				var dlg = new dijit.Dialog({
					id : 'messageWindow',
					title : tittle,
					content: "" + text,
					onHide : function() {
						dijit.byId('messageWindow').destroyRecursive();
					}
				});
				
                var yesBtn = new Button({
                    label: "OK",
                    style : "margin: auto; padding-top: 20px; padding-bottom: 5px",
                    onClick : function() {
                        dlg.hide();
                    }
                 });

                var div = dojo.create('div', { style : {'text-align' : "center", 'padding' : "10px" } }, dlg.containerNode);
                dojo.create(yesBtn.domNode,{}, div);
				dlg.show();
			});
		},	
		/*
		 * Wysyla request get do serwera 
		 */
		requestGet :function (pageUrl, callback) {
			require(["dojo/_base/lang", "dojo/_base/xhr", "modules/ep"], function(lang, xhr, thisObj) {
			   var xhrGet =  xhr.get({
			    	url: pageUrl,
			    	handleAs: "text",
			    	preventCache: true,
			        load: callback,
			        error: function(err, ioArgs){
			    	   thisObj.showMsg(err);
			       }
			    });
		    });
		},
		requestGetJson :function (pageUrl, callback) {
			require(["dojo/_base/lang", "dojo/_base/xhr", "modules/ep"], function(lang, xhr, thisObj) {
			   var xhrGet =  xhr.get({
			    	url: pageUrl,
			    	handleAs: "json",
			    	preventCache: true,
			        load: callback,
			        error: function(err, ioArgs){
			    	   thisObj.showMsg(err);
			       }
			    });
		    });
		},
		requestPost: function(url, contentObject, callback) {
			dojo.xhrPost({
				url: url,
				content: contentObject,
		        load: function(response, ioArgs) {
		           callback(response);
		        },
		        error : function(error) {
		        	alert("Sprawdź połączenie internetowe !");
		        }
		   });
		},
		/*
		 * tworzymy dialog ok, anuluj
		 */
		createActionDialog : function(config) {
			require([ "dijit/Dialog", "dijit/form/Button", "modules/ep"], function(dialog, button ,thisObj) {

                var dialog = new dijit.Dialog({
                    title: config.title,
                    style: config.style,
                    content : config.content,
                    id: config.id,
					onHide : function() {
						dijit.byId(config.id).destroyRecursive();
						dijit.byId(config.formId).destroyRecursive();
					}
                });
                
                var div = dojo.create('div', {}, dialog.containerNode);
                dojo.style(dojo.byId(div), "padding", "5px");
                dojo.style(dojo.byId(div), "text-align", "center");

                var noBtn = new dijit.form.Button({
                            label: "Anuluj",
                            style: "margin: 10px",
                            onClick: function(){
                                dialog.hide();
                            }
                         });

                var yesBtn = new dijit.form.Button({
                            label: "OK",
                            style: "margin: 10px",
                            onClick : function() {
                            	
                            	config.beforeSubmit();
                            	
                            	config.onSuccess();
                                dialog.hide();
                            }
                         });
                //adding buttons to the div inside dialog
                dojo.create(yesBtn.domNode,{}, div);
                dojo.create(noBtn.domNode,{}, div);
                dialog.show();
			});
		},
		createFinanseChart : function() {
			require([
			         "dojox/charting/Chart",
			         "dojox/charting/themes/Charged",
			         "dojox/charting/plot2d/ClusteredBars",
			         "dojox/charting/action2d/Tooltip",
			         "dojox/charting/action2d/Highlight",
			         "dojox/charting/widget/SelectableLegend",
			         "dojox/charting/axis2d/Default",
			         "dojox/charting/action2d/Tooltip",
			         "modules/ep"
			        ], function(Chart, theme, ClusteredBars, Tooltip, Highlight, SelectableLegend, Default, Tooltip, ep) {
						
						var getTip = function(value) {
							return value + " zł";
						}
				
						var convertToSeriesData = function(data) {
							var arr = new Array();
							var i;
							var item;
							for (i = 0; i < data.length; i++ ) {
								item = new Object();
								item.y = data[i].kwota;
								item.tooltip = getTip(item.y);
								
								arr.push(item);
							}
							return arr;
						};
				
						ep.getData(function(wydatkiData, dochodyData) {
							var dochodySeriesData = convertToSeriesData(dochodyData);
							var wydatkiSeriesData = convertToSeriesData(wydatkiData);
							
							var chart = new Chart("chartFinanse", {
								fill: 'rgba(1, 11, 78, 0.8)'
							});
							
							chart.addAxis("x", {
								vertical: false,
								title: "Kwota [zł]",
								titleOrientation: "away",
								titleFont: "normal normal normal 12pt Arial",
							    titleFontColor: "orange",
								stroke: "red",
								font: "normal normal bold 10pt Tahoma",
								fontColor: "#fff",
								majorTick: {length: 6, stroke: "red", color: "white"},
								minorTick: {stroke: "red", length: 3, color: "white"}
							});
							
							chart.addAxis("y", {
								vertical: true,
								natural: false,
								title: "Miesiąc",
								titleFont: "normal normal normal 12pt Arial",
							    titleFontColor: "orange",
								stroke: "red",
								fontColor: "#fff",
								labels: [
								         {value: 1, text: "Styczeń"}, {value: 2, text: "Luty"},
								         {value: 3, text: "Marzec"}, {value: 4, text: "Kwiecień"},
								         {value: 5, text: "Maj"}, {value: 6, text: "Czerwiec"},
								         {value: 7, text: "Lipiec"}, {value: 8, text: "Sierpień"},
								         {value: 9, text: "Wrzesień"}, {value: 10, text: "Październik"},
								         {value: 11, text: "Listopad"}, {value: 12, text: "Grudzień"}]
							});
								
							chart.addPlot("default", {type: ClusteredBars, gap: 5, animate:{duration: 1000}, vMajorLines: true, hMajorLines: true, enableCache: true});
							
					        var hoverAnim = new Highlight(chart, "default", {
					        	duration: 2,
					        	easing:   dojo.fx.easing.bounceOut
					        });
					       	var tooltipAnim = new Tooltip(chart, "default");
					       	
					       	chart.addSeries("Wydatki", wydatkiSeriesData,
									{/*stroke: {color: "white"}, fill: "#2D2A61"*/}
							);
					       	chart.addSeries("Dochody", dochodySeriesData,
									{/*stroke: {color: "white"}, fill: "#22CB00"*/}
							);
					       	
					       	chart.setTheme(theme).render();
					       	
				        	var legend = new SelectableLegend({ chart: chart, horizontal: true, style: 'margin:0px auto; color:#fff; padding:5px;', title: 'Legenda' }, "legend1");							
						});

				});
		}
		,
		getData : function(callback) {
			require(['modules/ep'], function(ep) {
				var onSuccess = function(array, cb) {
					ep.requestGetJson('dochod!listGrouppedByMonth.action', function(response) {
			        	callback(array, response);
		        	});
				};
				ep.requestGetJson('wydatek!listGrouppedByMonth.action', function(response) {
					onSuccess(response, callback);
	        	});
			})
		}
	}
});